﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using LDSP.Helper;

namespace LDSP.UI.Admin
{
    public partial class MngAuthentication : LDSP.BRL.BaseSysAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitData();
                        this.BindGrid();
                        this.BindTree();
                        this.BindCBLModules();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private int col_chk = 0;
        private int col_index = 1;
        private int col_code = 2;
        private int col_module = 3;
        private int col_op = 4;

        protected Enterprise m_enterprise = null;
        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "code";
            g_pageInfo.PageSize = GetPageSizeSetting();
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }
        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_enterprise = null;
                this.lbl_enterprise.Text = value == 0 ? "" : ("[" + Enterprise.Code + "]被授权的");
                this.lbl_module.Text = value == 0 ? "" : ("[" + Enterprise.Code + "]被授权的");
            }
        }

        protected Enterprise Enterprise
        {
            get
            {
                if (m_enterprise == null)
                {
                    m_enterprise = new Enterprise();
                    if (LastID != 0)
                    {
                        m_enterprise.GetProperties(LastID);
                    }
                }
                return m_enterprise;
            }
        }

        protected bool RB()
        {
            return this.AllowSystemUser();
        }
        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }

            this.SetSpecialPageInfo();
            BindDDLPageSize();
        }

        protected void BindDDLPageSize()
        {
            CommonControlInitial.InitialPageSize(this.ddl_pageSize);
            this.ddl_pageSize.SelectedValue = g_pageInfo.PageSize.ToString();
        }

        protected void InitDataDynamicBefore()
        {
        }
        protected void BindGrid()
        {
            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            this.grd_list.DataSource = BYFW.SFL.CommonOP.SortedTable(new Enterprise().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());
            this.grd_list.DataBind();

            SavePageSizeSetting();

            this.SetSelectedIndex();
        }
        protected void SetSelectedIndex()
        {
            this.grd_list.SelectedIndex = -1;
            for (int i = 0; i < this.grd_list.DataKeys.Count; i++)
            {
                if (this.GetInt(this.grd_list.DataKeys[i].Value) == LastID)
                {
                    this.grd_list.SelectedIndex = i;
                    break;
                }
            }
        }

        protected void BindCBLModules()
        {
            this.cbl_modules.Items.Clear();
            for (int i = 0; i < ModuleName.ModuleList.Count; i++)
            {
                this.cbl_modules.Items.Add(new ListItem(ModuleName.ModuleDic[ModuleName.ModuleList[i]], ModuleName.ModuleList[i]));
            }
        }

        protected void BindTree()
        {
            this.tre_obj.Nodes.Clear();
            List<Catalog> rootCatalogs = new Catalog().GetListRootByDefault();
            for (int i = 0; i < rootCatalogs.Count; i++)
            {
                TreeNode nd = new TreeNode();
                nd.Text = rootCatalogs[i].Name;
                nd.Value = rootCatalogs[i].ID.ToString();
                this.tre_obj.Nodes.Add(nd);
                this.BindTreeAssis(nd, rootCatalogs[i].ID);
            }
        }
        protected void BindTreeAssis(TreeNode parent, int parentID)
        {
            List<Catalog> catalogs = new Catalog().GetListByParentID(parentID);
            for (int i = 0; i < catalogs.Count; i++)
            {
                TreeNode nd = new TreeNode();
                nd.Text = catalogs[i].Name;
                nd.Value = catalogs[i].ID.ToString();
                parent.ChildNodes.Add(nd);
                this.BindTreeAssis(nd, catalogs[i].ID);
            }
        }
        protected void SetCheckedStatus()
        {
            List<R_EnterpriseCatalog> ecs = new R_EnterpriseCatalog().GetListByEnterpriseID(LastID);
            this.SetCheckedStatusAssis(ecs, this.tre_obj.Nodes);
        }
        protected void SetCheckedStatusAssis(List<R_EnterpriseCatalog> ecs, TreeNodeCollection tnc)
        {
            for (int i = 0; i < tnc.Count; i++)
            {
                bool find = false;
                for (int j = 0; j < ecs.Count; j++)
                {
                    if (this.GetInt(tnc[i].Value) == ecs[j].CatalogID)
                    {
                        tnc[i].Checked = true;
                        ecs.RemoveAt(j);
                        find = true;
                        break;
                    }
                }
                if (!find)
                {
                    tnc[i].Checked = false;
                }
                SetCheckedStatusAssis(ecs, tnc[i].ChildNodes);
            }
        }
        protected List<int> GetCheckedCatalogs()
        {
            List<int> cs = new List<int>();
            this.GetCheckedCatalogsAssis(cs, this.tre_obj.Nodes);
            return cs;
        }
        protected void GetCheckedCatalogsAssis(List<int> cs, TreeNodeCollection tnc)
        {
            for (int i = 0; i < tnc.Count; i++)
            {
                if (tnc[i].Checked)
                {
                    cs.Add(this.GetInt(tnc[i].Value));
                    CheckParentChecked(tnc[i], cs);
                }
                GetCheckedCatalogsAssis(cs, tnc[i].ChildNodes);
            }
        }
        protected void CheckParentChecked(TreeNode tn, List<int> cs)
        {
            if (tn.Parent != null)
            {
                int id = this.GetInt(tn.Parent.Value);
                if (!cs.Contains(id))
                {
                    cs.Add(id);
                }
                CheckParentChecked(tn.Parent, cs);
            }
        }

        protected void SetModuleCheckedStatus()
        {
            List<string> moduleList = Enterprise.GetModuleList();
            for (int i = 0; i < this.cbl_modules.Items.Count; i++)
            {
                this.cbl_modules.Items[i].Selected = moduleList.Contains(this.cbl_modules.Items[i].Value);
            }
        }
        protected string GetCheckedModules()
        {
            string res = ";";
            for (int i = 0; i < this.cbl_modules.Items.Count; i++)
            {
                if (this.cbl_modules.Items[i].Selected)
                {
                    res += this.cbl_modules.Items[i].Value + ";";
                }
            }
            return res;
        }

        protected void GetCondition()
        {
            string cond = "";
            if (this.txt_name.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLMultiCondition("code", EDataType.String, this.txt_name.Text.Trim(), true, true), true);
            }
            g_pageInfo.Condition = cond;
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.LastID = 0;
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                if (LastID > 0)
                {
                    new R_EnterpriseCatalog().DeleteByEnterprise(null, LastID);
                    List<int> cids = GetCheckedCatalogs();
                    for (int i = 0; i < cids.Count; i++)
                    {
                        R_EnterpriseCatalog rec = new R_EnterpriseCatalog();
                        rec.EnterpriseID = LastID;
                        rec.CatalogID = cids[i];
                        rec.Add();
                    }
                    this.SetCheckedStatus();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ok_module_Click(object sender, EventArgs e)
        {
            try
            {
                if (LastID > 0)
                {
                    Enterprise.Module = this.GetCheckedModules();
                    Enterprise.Update();
                    this.BindGrid();
                    JSAlert("操作已成功！");
                }
                else
                {
                    JSAlert("请选择企业进行授权！");
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                if (e.CommandName == "viewItem" && id > 0)
                {
                    LastID = id;
                    this.SetModuleCheckedStatus();
                    this.SetCheckedStatus();
                    this.SetSelectedIndex();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    this.ShowSequenceNumber(e.Row, 1);
                    var ett = UIHelper.GetEntityFromGridViewRow<Enterprise>(e.Row);
                    e.Row.Cells[col_module].Text = UIHelper.GetModuleNames(ett.GetModuleList());
                }

            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void ddl_pageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                g_pageInfo.PageSize = this.GetInt(this.ddl_pageSize.SelectedValue);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
    }

}